package com.zone.domain.strategy.service.raffle.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zone.domain.strategy.model.entity.RuleTreeNodeEntity;
import com.zone.domain.strategy.model.entity.StrategyRuleEntity;
import com.zone.domain.strategy.model.valobj.RuleEnums;
import com.zone.domain.strategy.repository.IRuleTreeRepository;
import com.zone.domain.strategy.repository.IStrategyRepository;
import com.zone.domain.strategy.service.IRaffleRule;
import com.zone.types.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author: zongzi
 * @description: TODO
 * @date: 2025/2/27
 */
@Slf4j
@Service
public class RaffleRuleImpl implements IRaffleRule {
    @Autowired
    private IRuleTreeRepository ruleTreeRepository;
    @Autowired
    private IStrategyRepository strategyRepository;

    public Map<Integer, List<RuleTreeNodeEntity>> queryAwardTreeNodeMap(Long strategyId) {
        if (Objects.isNull(strategyId)) {
            throw new BizException("策略id不能为空");
        }
        // 查询规则树id集合
        List<StrategyRuleEntity> strategyRules = strategyRepository.queryStrategyRules(strategyId, RuleEnums.RuleModelEnum.TREE.getCode());
        List<String> treeIds = strategyRules.stream().map(StrategyRuleEntity::getRuleValue).collect(Collectors.toList());
        Map<String, List<RuleTreeNodeEntity>> ruleTreeMap = ruleTreeRepository.queryTreeNodeListByTreeId(treeIds).stream().collect(Collectors.groupingBy(RuleTreeNodeEntity::getTreeId));
        // 构建返回结果
        Map<Integer, List<RuleTreeNodeEntity>> resultMap = Maps.newHashMap();
        strategyRules.forEach(strategyRuleEntity -> {
            List<RuleTreeNodeEntity> ruleTreeNodeEntityList = ruleTreeMap.getOrDefault(strategyRuleEntity.getRuleValue(), Lists.newArrayList());
            resultMap.put(strategyRuleEntity.getAwardId(), ruleTreeNodeEntityList);
        });
        return resultMap;
    }

    @Override
    public StrategyRuleEntity queryStrategyRule(Long strategyId, RuleEnums.RuleModelEnum ruleModelEnum) {
        return strategyRepository.queryStrategyRule(strategyId, RuleEnums.RuleTypeEnum.STRATEGY, ruleModelEnum);
    }
}
